package com.xhsd.zlong.generatecode.impl;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.xhsd.zlong.generatecode.IGenerator;
import com.xhsd.zlong.generatecode.model.IModelFactory;
import com.xhsd.zlong.generatecode.model.ITable;
import com.xhsd.zlong.generatecode.model.impl.mysql.MysqlModelFactory;
import com.xhsd.zlong.generatecode.process.IProcessor;
import com.xhsd.zlong.generatecode.process.freemark.imp.Processor;

import freemarker.template.TemplateException;

public class Generator implements IGenerator {
	private IModelFactory modelFactory;
	
	private IProcessor processor;
	
	private Generator(String url,String username,String passwd) throws ClassNotFoundException{
		processor=new Processor();
		
		modelFactory=MysqlModelFactory.getInstance(url, username, passwd);
		
	}
	
	public static IGenerator getInstance(String url,String username,String passwd) throws ClassNotFoundException{
		
		return new Generator(url, username, passwd);
	}

	@Override
	public void generate(String table,String genDir) throws IOException, TemplateException, SQLException {
		
		File dir=new File(genDir);
		
		if(!dir.exists()) dir.mkdirs();
		
		ITable tableModel = modelFactory.getTable(table);
		
		processor.process(tableModel, dir.getAbsolutePath()+File.separator+tableModel.getJavaNameLowerAll());

	}

	@Override
	public void generate(String genDir) throws SQLException, IOException, TemplateException {
		
		List<ITable> tableModels=modelFactory.getTables();
		
		for(ITable tableModel:tableModels){
			
			generate(tableModel.getName(), genDir);
		}

	}

}
